package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.outerlink.OuterLinkRegistry;
import com.xbongbong.paas.outerlink.interfaces.PaasOuterLinkService;
import com.xbongbong.paas.pojo.dto.FormDataRepeatDTO;
import com.xbongbong.paas.pojo.dto.OuterLinkAddDTO;
import com.xbongbong.paas.pojo.dto.OuterLinkAddGetDTO;
import com.xbongbong.paas.pojo.dto.OuterLinkBaseDTO;
import com.xbongbong.paas.pojo.dto.OuterLinkListDTO;
import com.xbongbong.paas.pojo.vo.CheckRepeatVO;
import com.xbongbong.paas.pojo.vo.FormDataAddGetVO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateGetVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.service.OuterLinkService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.ProFormDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.businessdata.pojo.dto.SpecificationHistoryDTO;
import com.xbongbong.pro.businessdata.pojo.vo.SpecificationHistoryVO;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.label.pojo.dto.LabelListDTO;
import com.xbongbong.pro.label.pojo.dto.LabelShowVO;
import com.xbongbong.pro.service.aliyun.AliyunOssService;
import com.xbongbong.saas.service.LabelService;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import java.util.Objects;

/**
 * @author long.rao
 * @version v1.0
 * @date 2020/8/10 9:10
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/outerLink")
public class OuterLinkController {

    private static final Logger LOG = LoggerFactory.getLogger(OuterLinkController.class);

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private AliyunOssService aliyunOssService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private ProFormDataService proFormDataService;
    @Resource
    private LabelService labelService;

    @Resource
    private OuterLinkRegistry outerLinkRegistry;


    /**
     * 获取外链查询列表页
     *
     * @param outerLinkDTO
     * @param br
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid OuterLinkListDTO outerLinkDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasOuterLinkService paasOuterLinkService = outerLinkRegistry.getExecutor(outerLinkDTO.getToken());
                PaasFormDataEsListVO appearance = paasOuterLinkService.getList(outerLinkDTO);
                response = new XbbResponse<>(appearance);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 获取外链详情页
     *
     * @param outerLinkBaseDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String get(@RequestBody @Valid OuterLinkBaseDTO outerLinkBaseDTO, BindingResult br) throws Exception {
        XbbResponse<FormDataUpdateGetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasOuterLinkService paasOuterLinkService = outerLinkRegistry.getExecutor(outerLinkBaseDTO.getToken());
                FormDataUpdateGetVO formDataUpdateGetVO = paasOuterLinkService.get(outerLinkBaseDTO);
                response = new XbbResponse<>(formDataUpdateGetVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 获取外链新建页
     *
     * @param outerLinkAddGetDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addGet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addGet(@RequestBody @Valid OuterLinkAddGetDTO outerLinkAddGetDTO, BindingResult br) throws Exception {
        XbbResponse<FormDataAddGetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                PaasOuterLinkService paasOuterLinkService = outerLinkRegistry.getExecutor(outerLinkAddGetDTO.getToken());
                FormDataAddGetVO formDataAddGetVO = paasOuterLinkService.addGet(outerLinkAddGetDTO);
                response = new XbbResponse<>(formDataAddGetVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 外链新建保存
     *
     * @param outerLinkAddDTO
     * @param br
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(@RequestBody @Valid OuterLinkAddDTO outerLinkAddDTO, BindingResult br, HttpServletRequest request) throws Exception {
        XbbResponse<FormDataAddVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(outerLinkAddDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(outerLinkAddDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            try {
                PaasOuterLinkService paasOuterLinkService = outerLinkRegistry.getExecutor(outerLinkAddDTO.getBusinessType());
                FormDataAddVO formDataAddVO = paasOuterLinkService.add(outerLinkAddDTO);
                response = new XbbResponse<>(formDataAddVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 外链获取aliyun oss签名，给前端用于文件上传
     *
     * @param
     * @param br
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/aliyun/oss/getSignature", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(@RequestBody @Valid BaseDTO baseDTO, BindingResult br, HttpServletRequest request) throws Exception {
        XbbResponse<Map<String, Object>> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            String corpid = baseDTO.getCorpid();
            Integer status = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.CAPACITY_NUM, 0);
            if (!Objects.equals(status, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(status, PackageStatusEnum.WARNING.getCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, "存储量已达上限，可联系客服购买容量！");
            }
            try {
                Map<String, Object> resultMap = aliyunOssService.getSignature();
                response = new XbbResponse<>(resultMap);
            } catch (XbbException xe) {
                response = new XbbResponse<>(xe);
            } catch (Exception e) {
                LOG.error("计算签名时出错", e);
                //TODO 去除魔法值
                response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100001, "获取签名相关参数出错");
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 外链获取aliyun sts oss签名，给前端用于文件上传
     *
     * @param
     * @param br
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/aliyun/oss/sts/getSignature", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getStsSignature(@RequestBody @Valid BaseDTO baseDTO, BindingResult br, HttpServletRequest request) throws Exception {
        XbbResponse<Map<String, Object>> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            String corpid = baseDTO.getCorpid();
            Integer status = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.CAPACITY_NUM, 0);
            if (!Objects.equals(status, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(status, PackageStatusEnum.WARNING.getCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, "存储量已达上限，可联系客服购买容量！");
            }
            try {
                Map<String, Object> resultMap = aliyunOssService.getOuterLinkStsSignature(baseDTO);
                response = new XbbResponse<>(resultMap);
            } catch (XbbException xe) {
                response = new XbbResponse<>(xe);
            } catch (Exception e) {
                LOG.error("计算签名时出错", e);
                //TODO 去除魔法值
                response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100001, "获取签名相关参数出错");
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 外链获取repeat接口
     *
     * @param
     * @param br
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/form/data/repeat", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String repeat(@RequestBody @Valid FormDataRepeatDTO formDataRepeatDTO, BindingResult br) {
        XbbResponse<CheckRepeatVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                CheckRepeatVO checkRepeatVO = paasFormDataService.repeat(formDataRepeatDTO);
                response = new XbbResponse<>(checkRepeatVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);

    }

    /**
     * 外链获取产品多规格记忆
     *
     * @param
     * @param br
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/form/data/specificationHistory", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String specificationHistory(@RequestBody @Valid SpecificationHistoryDTO specificationHistoryDTO, BindingResult br) {
        XbbResponse<SpecificationHistoryVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                SpecificationHistoryVO specificationHistoryVO = proFormDataService.specificationHistory(specificationHistoryDTO);
                response = new XbbResponse<>(specificationHistoryVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);

    }

    /**
     * 外链获取标签
     *
     * @param
     * @param br
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/label/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String labelList(@RequestBody @Valid LabelListDTO labelListDTO, BindingResult br) {
        XbbResponse<LabelShowVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                LabelShowVO labelShowVO = labelService.getAllLabelList(labelListDTO);
                response = new XbbResponse<>(labelShowVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);

    }

}
